今天我們又請來了貓貓當我們助教囉~~~

Day03_圖片剪裁旋轉縮放_crop_rotate_resize.ipynb
裁減圖片的方式,不需要使用 OpenCV 特別的函數,
我們只需要知道座標後,決定要裁減的範圍即可。
def crop_img(img):
    
    # left, right
    x_l, x_r = 300, 700 
    
    # up, down
    y_u, y_d = 0, 400 
    # crop image
    crop_img = img[y_u:y_d, x_l:x_r]  # notice: first y, then x
    
    return crop_img
你可能會想問,那要怎麼知道圖片的座標呢? 這也太難找了吧!
其實我們昨天就埋了一個梗在這哈哈哈哈哈,
如果昨天顯示圖片是使用在 jupyter 中直接顯示圖片的方式(透過 matplotlib),
那找座標就非常簡單了!
例如這張可愛貓貓的圖片:

我們可以大概抓一下,我抓 x=300, x=700,
至於y軸因為我想讓圖片裁剪出來為正方形 (400*400),所以我抓 y=0, y=400。
裁剪出來的效果大概就像這樣囉~

旋轉圖片我們使用 cv2.getRotationMatrix2D 的方式。
def rotate_img(img):
    (h, w, d) = img.shape # 讀取圖片大小
    center = (w // 2, h // 2) # 找到圖片中心
    
    # 第一個參數旋轉中心,第二個參數旋轉角度(-順時針/+逆時針),第三個參數縮放比例
    M = cv2.getRotationMatrix2D(center, 15, 1.0)
    
    # 第三個參數變化後的圖片大小
    rotate_img = cv2.warpAffine(img, M, (w, h))
    
    return rotate_img

縮放圖片我們使用 cv2.resize。
def resize_img(img):
    scale_percent = 50 # 要放大縮小幾%
    width = int(img.shape[1] * scale_percent / 100) # 縮放後圖片寬度
    height = int(img.shape[0] * scale_percent / 100) # 縮放後圖片高度
    dim = (width, height) # 圖片形狀 
    resize_img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)  
    
    return resize_img

在 jupyter notebook 中,直接顯示的圖片結果看不出大小差異,
我們可以使用前篇文章中的 cv2.imshow ,
這樣就可以明顯看出圖片大小的變化。
https://www.chainnews.com/zh-hant/articles/420945635518.htm
https://blog.gtwang.org/programming/how-to-crop-an-image-in-opencv-using-python/
https://www.cnblogs.com/lfri/p/10596530.html
https://blog.csdn.net/JNingWei/article/details/78218837
https://blog.csdn.net/on2way/article/details/46801063